package iscript.gameFramework.GameLite.content 
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.core.LoaderCore;
	import com.greensock.loading.data.LoaderMaxVars;
	import com.greensock.loading.data.XMLLoaderVars;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.LoaderStatus;
	import com.greensock.loading.XMLLoader;
	import flash.utils.Dictionary;
	import iscript.gameFramework.GameLite.events.GameContentEvent;
	

	internal class XMLLoaderContent implements IGameContent
	{
		
		private var _data:Dictionary = new Dictionary();	
		private var _loaderMax:LoaderMax;
		private var _gameContent:GameContent;
		
		
		public function XMLLoaderContent(gameContent:GameContent) 
		{
			   _gameContent = gameContent
			   var loadvars:LoaderMaxVars = new LoaderMaxVars();
				   loadvars.autoLoad(true);
				   loadvars.maxConnections(3);
				   loadvars.onChildComplete(_onChildCompleteLogic)
				   _loaderMax = new LoaderMax(loadvars);
				   _loaderMax.load();
		}
		
		private function _onChildCompleteLogic(e:LoaderEvent):void 
		{
			   _dispatch( XMLLoader(e.target));
		}
		
		private function _dispatch(load:XMLLoader):void {
			   var xmload:XMLLoader = load;
			   var event:GameContentEvent = new GameContentEvent(GameContentEvent.ONLOADXML);
			       event.content =  xmload;
				   event.key = xmload.vars[GameContent.GamneContentKey];
			       _gameContent.dispatchEvent(event);
				   
				 var ev:GameContentEvent = new GameContentEvent(GameContentEvent.EVERYTHING)
				     ev.key = xmload.vars[GameContent.GamneContentKey];
					 ev.content = xmload;
					 _gameContent.dispatchEvent(ev);
			}
		//public function get KEY():Array{return _data.getAllKeys()}	
		/**
		 * often time key==url   经常碰到把URL作为KEY，所以用的时候key和url经常是一个值.
		 * @param	key
		 * @param	url
		 * @param	param
		 */
		public function add(url:String,key:*,param:XMLLoaderVars = null):void { 
			if(_data[key]==null) {
			if (param == null)  param = new XMLLoaderVars();
					param.vars[GameContent.GamneContentKey] = key;
			   var  xmload:XMLLoader = new XMLLoader(url,param);
					_data[key] = xmload;
					_loaderMax.append(xmload);
				};
		}
		 
         
		public function addXMLoader(key:*, xmloader:XMLLoader):void {
			 if (xmloader.status == LoaderStatus.COMPLETED) {
				   //if (_data.add(key, xmloader)) {
				if (_data[key] == null) {
					_data[key] = xmloader;
				    _dispatch(xmloader) 
					  }
				 }
		}
			
		
		public function get(key:*):XMLLoader
		{
			return _data[key]
		}
		
		public function contain(key:*):Boolean
		{
			return _data[key] != null;
		}
		
		public function remove(key:*):void
		{
			if (_data[key] != null) {
			    LoaderCore(_data[key]).unload();
			    LoaderCore(_data[key]).dispose();
				delete _data[key];		
			}
		}
	}

}